package com.workspace.chb_website.service;

import com.workspace.chb_website.bean.User;
import com.workspace.chb_website.bean.Role;
import com.workspace.chb_website.bean.RespBean;
import com.workspace.chb_website.bean.MetaBean;
import com.workspace.chb_website.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    private final UserMapper userMapper;

    @Autowired
    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //security自动调用
        //根据用户名查询用户的角色信息，并返回存入user中
        User user = userMapper.loadUserByUsername(username);
        //避免返回null，这里返回一个不含有任何值的User对象，在后期的密码比对过程中一样会验证失败
        if (user == null) {
            return new User();
        }
        Role role = new Role();
        role.setName(user.getRole());
        List<Role> roles = new ArrayList<>();
        roles.add(role);
        user.setRoles(roles);
        return user;
    }

    public RespBean updatePassword(User user, String oldPassword, String newPassword) {
        if (user == null) {
            MetaBean meta = new MetaBean(400, "用户尚未登录!");
            return new RespBean("", meta);
        }
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bcryptPasswordEncoder.matches(oldPassword, user.getPassword())) {
            MetaBean meta = new MetaBean(400, "旧密码不正确!");
            return new RespBean("", meta);
        }
        newPassword = new BCryptPasswordEncoder().encode(newPassword);
        userMapper.updatePassword(user.getId(), newPassword);
        MetaBean meta = new MetaBean(200, "密码修改成功!");
        return new RespBean("", meta);
    }
}
